<?php
/**
 * Created by PhpStorm.
 * User: fengbob
 * Date: 2018/2/24
 * Time: 21:38
 */

namespace app\controllers;


use app\librarys\ApiResponseCode;
use app\librarys\BaseApiController;
use app\librarys\ExpressQuery;
use app\librarys\Tools;
use app\librarys\ZfbService;
use app\models\CategoryExt;
use app\models\db\Ad;
use app\models\db\Address;
use app\models\Area;
use app\models\db\Cart;
use app\models\db\Category;
use app\models\CategoryQuery;
use app\models\db\Discount;
use app\models\db\EShop;
use app\models\EShopExt;
use app\models\db\Express;
use app\models\db\Favourite;
use app\models\db\Goods;
use app\models\db\MiniPrograms;
use app\models\DiscountExt;
use app\models\File;
use app\models\GoodsBak;
use app\models\GoodsExt;
use app\models\db\GoodsDetailHtml;
use app\models\db\GoodsImage;
use app\models\db\Order;
use app\models\db\OrderGoods;
use app\models\db\TUser;
use app\models\GoodsQuery;
use app\models\MiniProgramsExt;
use app\models\TUserExt;
use app\models\User;
use Faker\Provider\DateTime;
use Yii;
use yii\db\Exception;
use yii\db\Query;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
class ApiZfbController extends BaseApiController
{
    private $current_mini_program = null;
    private $current_eshop = null;
    private $current_user = null;

    public function beforeAction($action)
    {

        if (self::IsFormRequest == true) {
            $this->_request = \Yii::$app->request;
        } else {
            $this->_request = json_decode(file_get_contents("php://input"));
        }
        $token = $this->_getRequestValue('access_token');

        $this->current_user = TUserExt::getZFBCurrentUser($token);

        $this->current_mini_program = TUserExt::getZFBCurrentMiniProgram($token);

        if(empty($this->current_user) || empty($this->current_mini_program)){
            echo $this->renderJson(null, ApiResponseCode::UserSessionErrorCode, ApiResponseCode::UserSessionErrorMessage);
            return false;
        }

        return parent::beforeAction($action);
    }

    /**
     * 评论查询
     */
    public function actionGetDiscount(){
        $order_goods_id = $this->_getRequestValue('order_goods_id');
        $discount = Discount::findOne(['order_goods_id'=>$order_goods_id]);

//        var_dump($discount);
        $query = (new Query())
            ->select(['t1.id','t3.url'])
            ->from('t_goods as t1')
            ->leftJoin('t_goods_image as t2','t1.id=t2.goods_id')
            ->leftJoin('t_file as t3','t2.file_id=t3.id')
            ->leftJoin('t_order_goods as t4','t4.goods_id=t1.id')
//            ->leftJoin('t_goods as t5','t5.id=t4.goods_id')
            ->where(['or','t2.`type`=1',['or','isnull(t2.`type`)']])
            ->andWhere(['t4.id'=>$order_goods_id])
            ->one();
//        var_dump($query->rawSql);
//        exit();
        $data = [];
        $data['discount'] = $discount->attributes;
        $data['goods'] = $query;
        return $this->renderJson($data,0,'success');
    }



    /**
     * 添加评论
     */
    public function actionAddDiscount(){
        $content = $this->_getRequestValue('content');
        $order_goods_id = $this->_getRequestValue('order_goods_id');
        $goods_score = $this->_getRequestValue('goods_score',5);
        $express_pack = $this->_getRequestValue('express_pack',5);
        $express_speed = $this->_getRequestValue('express_speed',5);
        $express_felling = $this->_getRequestValue('express_felling',5);

        $user = $this->current_user;



        $discount = DiscountExt::getDiscount($user["id"],$order_goods_id);

//        var_dump($discount);


        if(empty($discount)) {
            $discount = new Discount();
            $discount->id = Tools::db_uuid();

        }
        $discount->order_goods_id = $order_goods_id;
        $discount->goods_score = $goods_score;
        $discount->express_pack = $express_pack;
        $discount->express_speed = $express_speed;
        $discount->express_felling = $express_felling;
        $discount->content = $content;
        $discount->user_id = $user["id"];
//        var_dump($discount->user_id);
//        var_dump($discount);

        $result = $discount->save();

        return $this->renderJson($result,$result >0,'success');

    }

    /**
     * 快递查询
     * @return mixed
     */
    public function actionExpressQuery(){
//        $request = \Yii::$app->request;
        $express_no = $this->_getRequestValue('express_no');
//        \app\librarys\ExpressQuery::query($express_no);
        $result = ExpressQuery::query($express_no);
        return $result;
    }

    /**
     * 通过客户端auth_code，调用支付宝auth.token接口，获取token&uid
     */
    public function actionAuth(){
        $auth_code = $this->_getRequestValue('auth_code');
        $app_id = $this->_getRequestValue('app_id');
        $mini_programs = TUserExt::getByAppId($app_id);
        $result = ZfbService::getAuthToken($auth_code,$mini_programs);
        return $this->renderJson($result, 0, '成功!');

    }

    public function actionDemo()
    {
        $p1 = $this->_getRequestValue('p1');
        $p2 = $this->_getRequestValue('p2');

        $data = [
            'return_data_0' => [$p1,$p2]
        ];
        return $this->renderJson($data);
    }

    /**
     * 获取分类列表
     */
    public function actionGetCategories()
    {
        //需从内存中得到
        $mini_program_id=$this->current_mini_program['id'];
        $category_id = $this->_getRequestValue('category_id','');

        $result = CategoryExt::getCategory($mini_program_id,$category_id);
        return  $this->renderJson($result);
    }

    /**
     * 获取首页商品
     */
    public function actionGetMainpageGoods(){
        $mini_p = $this->current_mini_program['id'];
        $goods_query = GoodsQuery::getMainGoodsList($mini_p);
        return $this->renderJson($goods_query);
    }

    /**
     * 获取店铺
     * @return string
     */
    public function actionGetEshops(){
        $eshops = (new Query())
            ->select(['*'])
            ->from(['t_e_shop'])
            ->where(['mini_programs_id'=>$this->current_mini_program->id])
            ->all();

        return $this->renderJson($eshops,empty($eshops) ? 1000:0,empty($eshops) ? 'fail':'success');
    }

    /**
     * 获取商品列表接口
     */
    public function actionGetGoodsList()
    {
        $mini_programs_id = '1';
        $category_id = $this->_getRequestValue('category_id','');
        $page_size = $this->_getRequestValue('page_size',20);
        $page = $this->_getRequestValue('page',0);
        $sort_price = $this->_getRequestValue('sort_price','');
        $sort_shelve_date = $this->_getRequestValue('sort_shelve_date','');
        $sort_sell_count = $this->_getRequestValue('sort_sell_count','');
        $sort_discount = $this->_getRequestValue('sort_discount','');
        $good_brand_ids = $this->_getRequestValue('good_brand_ids','');
        $is_new_goods = $this->_getRequestValue('is_newest','');
        $is_hot = $this->_getRequestValue('is_hot','');
        $is_promotion = $this->_getRequestValue('is_promotion','');
        $is_recommend = $this->_getRequestValue('is_recommend','');
        $is_free_express = $this->_getRequestValue('is_free_express','');

        $key_word = $this->_getRequestValue('key_word','');

//         var_dump($this);

        if(!empty($key_word)){
            //搜索
            return  $this->search($key_word,$page_size,$page,$mini_programs_id);

        }


        $query = (new \yii\db\Query())
            ->select(['t1.id','t1.name as goods_name','t7.url','t6.name as brand_name','t1.selling_price','t1.sell_count','t1.collected_count','t5.file_id'])
            ->from('t_goods as t1');

        $query->leftJoin('t_goods_brand_name as t6','t6.id=t1.goods_brand_name_id');
//            ->andWhere(['t6.id'=>t1.goods_brand_name_id]);

        if(!empty($is_new_goods)){
            $query->where(['is_newest'=> 1]);
        }

        if(!empty($category_id))
        {
            $query->leftJoin('t_goods_category_goods as t2','t1.id=t2.goods_id')
                ->leftJoin('t_goods_category as t3','t3.id=t2.goods_category_id')
                ->andWhere('t3.id=:category_id',[':category_id' => $category_id]);
        }

        if(!empty($good_brand_ids))
        {
            foreach ($good_brand_ids as $good) {
                $r[] = $good->good_brand_id;
            }
            $query->leftJoin('t_goods_brand_name as t6','t6.id=t1.goods_brand_name_id')
                ->andWhere(['t6.id'=>$r]);
        }

        $query->leftJoin('t_goods_image as t5','t5.goods_id=t1.id')
            ->leftJoin('t_file as t7','t7.id=t5.file_id')
            ->andFilterWhere(['t1.is_free_express'=>$is_free_express])
            ->andFilterWhere(['t1.is_recommend'=>$is_recommend])
            ->andFilterWhere(['t1.is_promotion'=>$is_promotion])
            ->andFilterWhere(['t1.is_hot'=>$is_hot])
            ->andWhere('t1.mini_programs_id=:mini_programs_id',[':mini_programs_id'=>$mini_programs_id])
            ->andWhere(['t1.is_enabled' => 1,'t1.is_shelved' => 1])
            ->andWhere(['or','t5.`type`=1',['or','isnull(t5.`type`)']])
            ->offset($page)
            ->limit($page_size)
            ->all();

        if(!empty($sort_shelve_date)){
            if($sort_shelve_date == 1)
                $query->orderBy(['shelve_datetime' => SORT_ASC]);
            else
                $query->orderBy(['shelve_datetime' => SORT_DESC]);
        }

        if(!empty($sort_price)){
            if($sort_price == 1)
                $query->orderBy(['t1.selling_price' => SORT_ASC]);
            else
                $query->orderBy(['t1.selling_price' => SORT_DESC]);
        }

        if(!empty($sort_discount)){
            if($sort_discount == 1)
                $query->orderBy(['selling_price' => SORT_ASC]);
            else
                $query->orderBy(['selling_price' => SORT_DESC]);
        }

        if(!empty($sort_sell_count)){
            if($sort_sell_count == 1)
                $query->orderBy(['sell_count' => SORT_ASC]);
            else
                $query->orderBy(['sell_count' => SORT_DESC]);
        }

        $command = $query->createCommand();

        $rows = $command->queryAll();
//        array_push($rows,["is_hot"=>$this]);
//        var_dump($this);
        return $this->renderJson($rows);
    }


    /**
     * 获取商品详情
     */
    public function actionGetGood()
    {
        $goods_id = $this->_getRequestValue('goods_id');


        $query = (new Query())
            ->select(['t1.*','t3.url'])
            ->from(['t_goods as t1'])
            ->leftJoin('t_goods_image as t2','t2.goods_id = t1.id')
            ->leftJoin('t_file as t3','t3.id = t2.file_id')
            ->where(['t1.id'=>$goods_id])
            ->one();


        if(empty($query))
            return $this->renderJson(null, ApiResponseCode::OtherErrorCode, '没有订单哟!');


        $imgs = GoodsImage::findAll(['goods_id'=>$goods_id,'type'=>2]);
        $imgs_detal =  GoodsImage::findAll(['goods_id'=>$goods_id,'type'=>3]);


//            $query2 = (new Query())
//                ->select('image_url')
//                ->from('t_goods_image')
//                ->where(['goods_id'=>$goods_id,'type'=>2])
//                ->all();
//                ->createCommand();
//            var_dump($query2->rawSql);
        $i=0;
        foreach ($imgs as $img){

            $query['images'][$i]= File::getFile($img->file_id);
            $i = $i + 1;
        }

        $i=0;
        foreach ($imgs_detal as $img){

            $query['images_detail'][$i]= File::getFile($img->file_id);
            $i = $i + 1;
        }

//            $query['images'] = $query2;




        return $this->renderJson($query, 0, 'success!');


//        $good_html = GoodsDetailHtml::findOne($goods_id);
//        if($good_html == null)
//            $good_html= new GoodsDetailHtml();
//        $good = Goods::findOne($goods_id);
//        if($good == null)
//            $good = new Goods();
//        //$imgs = $good->getGoodsImages(["type"=>2]);
////        foreach ($imgs as $img)
////        {
////            $i [] = ["imgs"=>$img->image_url];
////        }
//        $re[] =["good"=>$good->attributes];
//        foreach ($good->getGoodsImages()->where(["type"=>2])->all() as $url){
//            $re[] =["img"=>$url->image_url];
//        }
//
//        return $this->renderJson($re);
    }

    /**
     * 获取广告列表
     * @return string
     */
    public function actionGetAds()
    {
//        $mini_program_id = $this->_getRequestValue('mini_program_id');
//        var_dump('1');

        $mini_program_id = $this->current_mini_program['id'];
//        var_dump($mini_program_id);
        $ad_category_id = $this->_getRequestValue('ad_category_id');

        $query = (new Query())
            ->select(['t2.url as imgUrls'])
            ->from(['t_ad as t1'])
            ->leftJoin('t_file as t2','t2.id = t1.image_id')
            ->where(['t1.mini_program_id'=>$mini_program_id,'t1.ad_category_id'=>$ad_category_id,'is_shown'=>1,'is_deleted'=>0])
            ->orderBy('sort')
            ->all();

        foreach ($query as $im){
            $re [] = $im['imgUrls'];
//            var_dump($im['imgUrls']);
        }

        if(empty($re))
        {
            $re = '';
        }
        return $this->renderJson($re);
    }


    /**
     * 搜索
     * @return string
     */
    public function search($key_word,$page_size,$page,$mini_program_id)
    {
//        $mini_program_id = 1;
//        $key_word = $this->_getRequestValue('key_word');
//        $page_size = $this->_getRequestValue('page_size',20);
//        $page = $this->_getRequestValue('page',0);


        $query = (new \yii\db\Query())
            ->select(['t_goods.id','t_goods.name as goods_name','display_name','subtitle','short_name','is_recommend','is_newest','is_hot',
                'is_free_express','is_promotion','is_top','selling_price','old_price','is_invoice','is_GGCT',
                'is_seven_day','is_return_goods','sell_count','collected_count','t3.url'])
            ->from(['t_goods'])
            ->leftJoin('t_goods_image','t_goods_image.goods_id = t_goods.id')
            ->leftJoin('t_file as t3','t3.id = t_goods_image.file_id')
            ->where(['like','t_goods.name',$key_word])
            ->orWhere(['like','subtitle',$key_word])
            ->orWhere(['like','short_name',$key_word])
            ->orWhere(['like','summary',$key_word])
//            ->andWhere(['t_goods_image.`type`'=>1])
            ->andWhere(['or','t_goods_image.`type`=1',['or','isnull(t_goods_image.`type`)']])
//            ->orWhere(['t_goods_image.`type`'=>null])
            ->andWhere(['mini_programs_id'=>"$mini_program_id"])
            ->limit($page_size)
            ->offset($page)
            ->all();

        return $this->renderJson($query);

    }

    /**
     * 获取收藏列表
     * @return string
     */
    public function actionGetFavorite(){
        $user_id = $this->current_user['id'];
        $mini_programe_id = $this->current_mini_program['id'];

        $query = (new Query())
            ->select(['t1.id as favorite_id','t2.id as good_id','t2.name as good_name','t2.selling_price as good_selling_price','t2.sell_count as good_selling_count',
                't2.is_newest','t5.url as good_imageUrl','t4.name as good_brand'])
            ->from(['t_favourite as t1'])
            ->leftJoin('t_goods as t2','t1.good_id = t2.id')
            ->leftJoin('t_goods_image as t3','t3.goods_id=t2.id')
            ->leftJoin('t_file as t5','t5.id = t3.file_id')
            ->leftJoin('t_goods_brand_name as t4','t4.id=t2.goods_brand_name_id')
            ->where(['t1.user_id'=>"$user_id",'t1.mini_programs_id'=>"$mini_programe_id"])
            ->andWhere((['or','t3.`type`=1',['or','isnull(t3.`type`)']]))
            ->all();
        return $this->renderJson($query, 0, 'success!');
    }

    /**
     * 添加收藏
     * @return string
     */
    public function actionAddFavorite()
    {
//        var_dump('111');
        $goods_id = $this->_getRequestValue('goods_id');
//        $user_id = '1';
//        $mini_programe_id = '1';
        $mini_programe_id = $this->current_mini_program['id'];
        $user_id = $this->current_user['id'];

        $favorite = Favourite::findOne(['good_id'=>$goods_id,'user_id'=>$user_id,'mini_programs_id'=>$mini_programe_id]);
        if(!empty($favorite))
            return $this->renderJson('fail', 100, '已经收藏过这款商品了哟!');

        $favorite = new Favourite();
//        $favorite->good_id = $goods_id;
        $favorite->mini_programs_id = $mini_programe_id;
        $favorite->id = Tools::db_uuid();
        $favorite->good_id = "$goods_id";
        $favorite->user_id = "$user_id";
        try {
            $r = $favorite->insert();
            if(!$r)
                return $this->renderJson('fail', 300, '收藏失败!');

//            var_dump($r);
        }catch (Exception $e){
            var_dump($e);
        }
//       var_dump("r is $r.");

        return $this->renderJson($favorite->id, 0, '收藏成功!');
    }

    /**
     * 删除收藏
     * @return string
     */
    public function actionDelFavorite()
    {
        $favorite_id = $this->_getRequestValue('favorite_ids');
        $r = Favourite::deleteAll(['id'=>$favorite_id]);
        if($r<1)
            return $this->renderJson('fail', 8001, '删除失败!');

        return $this->renderJson('success', 0, '删除成功!');
    }


    public function actionGetAreasByCitycode(){
//        $areas = Area::findAll(['level'=>3]);
//        foreach ($areas as &$area){
//            $length = strlen($area->area_code_5);
//            echo "length:$length     ";
//             echo "code5:$area->area_code_5     ";
//            $str = $area->area_code_5;
//
//            for($i=0;$i<6-$length;$i++){
//                $str .='0';
//                echo "code5::$str   ";
//            }
//            $area->area_code_5 = $str;
//            echo "code5:::$area->area_code_5     ";
//
//            $area->save();
//        }
//
//        return;


        $city_code = $this->_getRequestValue('code','');
        $level = $this->_getRequestValue('level');

        if($level > 3 || $level < 1)
            return $this->renderJson('', -2, '不支持的level!');

//        if(empty($city_code))


        if($level==1)
            $city_code='0';
        $query = (new Query())
            ->select(['area_name','whole_name','id as area_code'])
            ->from(['t_area'])
            ->Where(['level'=>$level ,'parent_id'=>$city_code])
            ->all();

//        $query2 = (new Query())
//            ->select(['area_name'])
//            ->from(['t_area'])
//            ->Where(['level'=>$level])
//            ->andFilterWhere(['area_code'=>$city_code])
//            ->orderBy('area_name',SORT_ASC)
//            ->all();




        if(empty($query))
            return $this->renderJson('', -1, '不存在的城市!');
        $query2 =[];$i = 0;
        foreach ($query as &$item){
            $query2[$i] = $item['area_name'];
            $item['id'] = $i;
            $i = $i +1;
        }
        $re =[$query,$query2];


        return $this->renderJson($re, 0, 'success!');

    }

    /**
     * 添加收货地址
     * @return string
     */
    public function actionAddOrUpdateAddress()
    {
        $mini_program_id = $this->current_mini_program['id'];
        $user_id= $this->current_user['id'];
        $province = $this->_getRequestValue('province');
        $city = $this->_getRequestValue('city');
        $region = $this->_getRequestValue('region');
        $address = $this->_getRequestValue('address');
        $name = $this->_getRequestValue('name');
        $phone = $this->_getRequestValue('phone');
        $postcode = $this->_getRequestValue('postcode','');
        $address_id = $this->_getRequestValue('address_id','');

        if(empty($address_id))
            $add = new Address();
        else
            $add = Address::findOne($address_id);
        $add->id = Tools::db_uuid();
        $add->mini_program_id = $mini_program_id;
        $add->user_id = $user_id;
        $add->province_name = $province;
        $add->phone = $phone;
        $add->city_name = $city;
        $add->region_name = $region;
        $add->address = $address;
        $add->name = $name;
        if(!empty($postcode)){
            $add->postcode = $postcode;
        }

        $add->save();
        return $this->renderJson($add->id, 0, '添加成功!');
    }

    /**
     * 获取收货地址
     * @return string
     */
    public function actionGetAddress(){
        $address_id = $this->_getRequestValue('address_id','');
        $mini_program_id = $this->current_mini_program['id'];
        $user_id=$this->current_user['id'];
//        var_dump($this->current_user);
//        var_dump($this->current_mini_program);
        if(!empty($address_id)){
            $query = (new Query())
                ->select(['id,phone,name,CONCAT(province_name,city_name,region_name) as region,address,is_default'])
                ->from('t_address')
                ->where(['id'=>$address_id])
                ->one();
//            var_dump($query->rawSql);
            if(empty($query))
                return $this->renderJson('fail', -1, '获取地址失败!');
            return $this->renderJson($query, 0, 'success!');


        }




        $query = (new Query())
            ->select(['id,phone,name,CONCAT(province_name,city_name,region_name) as region,address,is_default'])
            ->from('t_address')
            ->where(['user_id'=>$user_id,'mini_program_id'=>$mini_program_id])
            ->all();

        if(empty($query))
            return $this->renderJson('fail', -1, '没有添加地址哟!');
        $has_default = false;
        foreach ($query as &$q){
//            var_dump($q);
            if($q['is_default'] == 1) {
                $q['is_default'] = true;
                $has_default = true;
            }
            else
                $q['is_default'] = false;
        }

        if(!$has_default) {
            $query[0]['is_default'] = true;
        }



        return $this->renderJson($query, 0, 'success!');


    }

    /**
     * 删除地址
     * @return string
     */
    public function actionDelAddress(){
        $address_id = $this->_getRequestValue('address_id');
        $add = Address::findOne($address_id);
        if(isset($add)){
            $add->delete();
            return $this->renderJson('success', 0, '删除地址成功!');
        }else{
            return $this->renderJson(null, ApiResponseCode::OtherErrorCode, '删除地址失败!');
        }
    }

    /**
     * 设置默认收货地址
     * @return string
     */
    public function actionSetDefaultAddress(){
        $mini_program_id = $this->current_mini_program['id'];
        $user_id=$this->current_user['id'];
        $address_id = $this->_getRequestValue('address_id');
        $add = Address::findOne($address_id);
        if(isset($add)){
            $add->is_default = 1;
            $add->save();

            $all = Address::findAll(['user_id'=>$user_id,'mini_program_id'=>$mini_program_id]);
            foreach ($all as $other)
            {
                if($other->id != $address_id){
                    $other->is_default = 0;
                    $other->save();
                }
            }

            return $this->renderJson('success', 0, '设置默认地址成功!');
        }else{
            return $this->renderJson(null, ApiResponseCode::OtherErrorCode, '设置默认地址失败!');
        }
    }

    /**
     * 修改地址
     * @return string
     */
    public function actionEditAddress(){
        $mini_program_id = '1';
        $user_id='1';
        $province = $this->_getRequestValue('province');
        $city = $this->_getRequestValue('city');
        $region = $this->_getRequestValue('region');
        $address = $this->_getRequestValue('address');
        $name = $this->_getRequestValue('name');
        $phone = $this->_getRequestValue('phone');
        $postcode = $this->_getRequestValue('postcode','');
        $address_id = $this->_getRequestValue('address_id');

        $add = Address::findOne($address_id);

        if(empty($add))
            return $this->renderJson(null, ApiResponseCode::OtherErrorCode, '修改地址失败!');

        $add->province_name = $province;
        $add->phone = $phone;
        $add->city_name = $city;
        $add->region_name = $region;
        $add->address = $address;
        $add->name = $name;
        if(!empty($postcode)){
            $add->postcode = $postcode;
        }

        $add->save();
        return $this->renderJson('success', 0, '添加成功!');

    }


    /**
     * 查询购物车产品种类数
     * @return string
     */
    public function actionGetCartCount()
    {
//        $user_id = '1';
//        $mini_program = '1';


        $mini_program = $this->current_mini_program['id'];
        $user_id = $this->current_user['id'];
        $query = (new Query())
            ->select(['count(*) as count'])
            ->from(['t_cart'])
            ->where(['user_id'=>$user_id,'mini_program'=>$mini_program]);

        return $this->renderJson($query->createCommand()->queryOne(), 0, 'success!');
    }

    public function actionBuyNow(){
        $goods_id = $this->_getRequestValue('goods_id');

        $mini_program = $this->current_mini_program['id'];
        $user_id = $this->current_user['id'];

//        $cart = Cart::findAll(['user_id'=>$user_id,'mini_program'=>$mini_program]);
//        $goods_ids = [];
//        if(!empty($cart)){
//            foreach ($cart as $goods){
//                $goods_ids[] = $goods->good_id;
//            }
//
//            $query = (new Query())
//                ->select(['t1.id as good_id','t3.url as good_img','t1.name as good_name','t1.selling_price as good_selling_price',
//                    'old_price as good_old_price','(select 1) as quantity'])
//                ->from(['t_goods as t1'])
//                ->leftJoin('t_goods_image as t2','t2.goods_id = t1.id')
//                ->leftJoin('t_file as t3','t3.id = t2.file_id')
//                ->where(['or','t2.`type`=1',['or','isnull(t2.`type`)']])
//                ->andWhere(['t1.id'=>$goods_ids])
//                ->all();
        $query = (new Query())
            ->select(['t1.id as good_id','t3.url as good_img','t1.name as good_name','t1.selling_price as good_selling_price',
                't1.old_price as good_old_price','(select 1) as quantity'])
            ->from(['t_goods as t1'])
            ->leftJoin('t_goods_image as t2','t2.goods_id = t1.id')
            ->leftJoin('t_file as t3','t3.id = t2.file_id')
//                ->where(['and','t1.id=t5.good_id','t5.user_id'=>$user_id])
            ->where(['or','t2.`type`=1',['or','isnull(t2.`type`)']])
            ->andWhere(['t1.id'=>$goods_id])
//            ->createCommand();
            ->all();


        return $this->renderJson($query, 0, 'success!');

//        }else{
//            return $this->renderJson('fail', -1, '没有收藏产品哟!');
//        }

    }

    /**
     * 过去购物车列表
     * @return string
     */
    public function actionGetCart(){
//        $user_id = '1';
//        $mini_program = '1';

        $mini_program = $this->current_mini_program['id'];
        $user_id = $this->current_user['id'];

//        $cart = Cart::findAll(['user_id'=>$user_id,'mini_program'=>$mini_program]);
//        $goods_ids = [];
//        if(!empty($cart)){
//            foreach ($cart as $goods){
//                $goods_ids[] = $goods->good_id;
//            }
//
//            $query = (new Query())
//                ->select(['t1.id as good_id','t3.url as good_img','t1.name as good_name','t1.selling_price as good_selling_price',
//                    'old_price as good_old_price','(select 1) as quantity'])
//                ->from(['t_goods as t1'])
//                ->leftJoin('t_goods_image as t2','t2.goods_id = t1.id')
//                ->leftJoin('t_file as t3','t3.id = t2.file_id')
//                ->where(['or','t2.`type`=1',['or','isnull(t2.`type`)']])
//                ->andWhere(['t1.id'=>$goods_ids])
//                ->all();
        $query = (new Query())
            ->select(['t1.id as good_id','t3.url as good_img','t1.name as good_name','t1.selling_price as good_selling_price',
                't1.old_price as good_old_price','t5.quantity'])
            ->from(['t_goods as t1'])
            ->leftJoin('t_goods_image as t2','t2.goods_id = t1.id')
            ->leftJoin('t_file as t3','t3.id = t2.file_id')
            ->leftJoin('t_cart as t5','t1.id=t5.good_id')
//                ->where(['and','t1.id=t5.good_id','t5.user_id'=>$user_id])
            ->where(['or','t2.`type`=1',['or','isnull(t2.`type`)']])
            ->andWhere(['t5.user_id'=>$user_id])
//            ->createCommand();
            ->all();


            return $this->renderJson($query, 0, 'success!');

//        }else{
//            return $this->renderJson('fail', -1, '没有收藏产品哟!');
//        }
    }


    /**
     * 设置购物车
     * 如没有此商品就添加，如有就修改数量
     * "goods_ids":[{"goods_id":"111","quantity":"2"},{"goods_id":"222","quantity":"23"}]
     */
    public function actionAddCart()
    {
//        $user_id = '1';
//        $mini_program = '1';
        $mini_program = $this->current_mini_program['id'];
        $user_id = $this->current_user['id'];

        $goods_ids = $this->_getRequestValue('goods_ids');
        if(!empty($goods_ids))
        {
            foreach ($goods_ids as $good) {
//                $r[] = $good->goods_id;
                $cart = Cart::findOne(['mini_program' => $mini_program,'user_id'=>$user_id,'good_id'=>$good->goods_id]);
                if(empty($cart)) {
                    $cart = new Cart();
                    $cart->id = Tools::db_uuid();
                    $cart->user_id = $user_id;
                    $cart->mini_program = $mini_program;
                    $cart->good_id = $good->goods_id;
                    $cart->quantity = 1;
                }else {
                    $cart->quantity = $cart->quantity+1;
                }
                $cart->is_selected = 1;
                $cart->save();
            }
            return $this->renderJson('success', 0, '添加购物车成功!');
        }
        return $this->renderJson(null, ApiResponseCode::OtherErrorCode, '添加购物车失败!');
    }


    /**
     * 删除购物车
     */
    public function actionDelCarts()
    {

//        $user_id = '1';
//        $mini_programs_id = '1';
        $mini_programs_id = $this->current_mini_program['id'];
        $user_id = $this->current_user['id'];

        $goods_ids = $this->_getRequestValue('goods_ids');

        if(!empty($goods_ids)){
            foreach ($goods_ids as $goods_id) {
                $carts = Cart::findAll(['user_id'=>$user_id,'mini_program'=>$mini_programs_id,'good_id'=>$goods_id]);
                if (!empty($carts)) {
                    foreach ($carts as $c)
                        $c->delete();
                }
            }
            return $this->renderJson('success', 0, '删除购物车成功!');
        }
        return $this->renderJson(null, ApiResponseCode::OtherErrorCode, '删除购物车失败!');
    }


    /**
     * 选中/未选中，反选
     */
    public function actionSetCartGoods(){
        $cart_id = $this->_getRequestValue('cart_id');
        if(!empty($cart_id)){
            $cart = Cart::findOne($cart_id);
            if(!empty($cart)){
                if($cart->is_selected){
                    $cart->is_selected = 0;
                }else{
                    $cart->is_selected = 1;
                }
                $cart->save();
                return $this->renderJson('success', 0, '设置购物车成功!');
            }
        }
        return $this->renderJson(null, ApiResponseCode::OtherErrorCode, '设置购物车失败!');
    }

    /**
     * 设置购物车所有为选中
     */
    public function actionSetAllCart(){
        $user_id = '1';
        $mini_program = '1';
        $carts = Cart::findAll(['user_id'=>$user_id,'mini_program'=>$mini_program]);
        foreach ($carts as $cart){
            $cart->is_selected = 1;
            $cart->save();
        }
        return $this->renderJson('success', 0, '设置成功!');
    }

    /**
     * 设置购物车所有为未选中
     */
    public function actionUnsetAllCart(){
        $user_id = '1';
        $mini_program = '1';
        $carts = Cart::findAll(['user_id'=>$user_id,'mini_program'=>$mini_program]);
        foreach ($carts as $cart){
            $cart->is_selected = 0;
            $cart->save();
        }
        return $this->renderJson('success', 0, '设置成功!');
    }


    /**
     * 设置订单收货地址
     */
    public function actionSetOrderAddress(){
        $user_id='1';
        $mini_program='1';
        $order_id = $this->_getRequestValue('order_id');
        $address_id = $this->_getRequestValue('address_id');

        $order = Order::find($order_id);
        $address = Address::find($address_id);
        if(!empty($order)){
            if(!empty($address)){
                var_dump($order);
                $order->receiver_province = $address->province;

            }else{
                //no address
            }
        }else{
            //no order
        }
    }

    /**
     * 下单
     * @throws \Exception
     * @throws \Throwable
     */
    public function actionAddOrder(){
        $user_id=$this->current_user['id'];
        $e_shop_id = $this->current_eshop['id'];
        $mini_program=$this->current_mini_program['id'];
        $goods = $this->_getRequestValue('goods');
        $address_id = $this->_getRequestValue('address_id');
        $remark = $this->_getRequestValue('remark');
//        return $this->renderJson($goods, ApiResponseCode::OtherErrorCode, '下单失败!');

        $transaction = Order::getDb()->beginTransaction();
        try {


            $order = new Order();
            $order->id = Tools::db_uuid();
            $order->mini_program = $mini_program;
            $order->e_shop_id = $e_shop_id;

            $order->is_deleted = 0;
            $address = Address::findOne($address_id);
            $order->receiver_address = $address->address;
            $order->receiver_city = $address->city_name;
            $order->receiver_name = $address->name;
            $order->receiver_postcode = $address->postcode;
            $order->receiver_phone = $address->phone;
            $order->receiver_province = $address->province_name;
            $order->receiver_region = $address->region_name;
            $order->receiver_remark = $remark;
            $temp = '';
            if(strlen($order->mini_program)>=2)
                $temp = substr($order->mini_program,0,2);
            else
                $temp = substr($order->mini_program,0,strlen($order->mini_program));

            $code = $temp;

            if(strlen($order->e_shop_id)>=2)
                $temp = substr($order->e_shop_id,0,2);
            else
                $temp = substr($order->e_shop_id,0,strlen($order->e_shop_id));

            $time = time();

            $code = $code . $temp .Tools::getDatetimeFormat($time, 'YmdHis').rand(10,99);

            $order->code = $code;

            $order->user_id = $user_id;
            $order->mini_program = $mini_program;
            $order->status = 1;
//            $order->create_datetime = date('y-m-d h:i:s',time());
            $order->total_selling_price = 0;
            $order->status = 1;

            $order->save();

            //总原价
            $total_old_price = 0;
            foreach ($goods as $good)
            {
                //del cart

                $carts = Cart::findAll(['good_id'=>$good->good_id]);

                foreach ($carts as $cart)
                    $cart->delete();

//                var_dump($good);
                $order_goods = new OrderGoods();
                $order_goods->id = Tools::db_uuid();
                $order_goods->goods_id = $good->good_id;
                $order_goods->quantity = $good->quantity;
                $order_goods->goods_name = $good->good_name;
                $order_goods->selling_price = $good->good_selling_price;
                $order_goods->save();
                $price = Goods::findOne($good->good_id);
                if(empty($price)){
                    $transaction->rollBack();
                    return $this->renderJson(null, ApiResponseCode::OtherErrorCode, '下单失败!');
                }
                $p = $order_goods->quantity;
//                echo $p;
                $t_p = $price->old_price;
//                echo "$t_p     $p    :";
                if(empty($price->old_price))
                    $total_old_price = $total_old_price + $price->sell_count*$p;
                else
                    $total_old_price = $total_old_price + $t_p*$p;

//                echo "$total_old_price .";
//                $total_old_price = $price->old_price;
                $order->total_selling_price = $order->total_selling_price + ($price->selling_price*$p);
                $order_goods->link('order',$order);
            }
            //总折扣
            $off_price =  $total_old_price - $order->total_selling_price;

            $order->save();
            // ...other DB operations...

            $data = ['total_selling_price' => $order->total_selling_price,'off_price' => $off_price,
                'total_old_price'=>$total_old_price];
            $transaction->commit();

            return $this->renderJson($data, 0, '设置成功!');
        } catch(\Exception $e) {
            $transaction->rollBack();
            throw $e;
        } catch(\Throwable $e) {
            $transaction->rollBack();
            throw $e;
        }
        return $this->renderJson(null, ApiResponseCode::OtherErrorCode, '下单失败!');
    }

    /**
     * 删除订单
     * @return string
     */
    public function actionDelOrder(){
        $order_id = $this->_getRequestValue('order_id');

        $order = Order::findOne($order_id);
        if(empty($order)){
            return $this->renderJson(null, ApiResponseCode::OtherErrorCode, '订单号不存在哟!');
        }

        $order->is_deleted = 1;
        $order->save();
//
//        foreach ($order->tOrderGoods as $good){
//            $good->delete();
//        }
//        $order->delete();
        return $this->renderJson('success', 0, '删除成功!');

    }

    /**
     * 获取各类订单数量
     * @return string
     */
    public function actionGetMyOrdersCount()
    {
        $mini_program = '1';
        $user_id = '1';
//        $orders = Order::findAll(['user_id' => $user_id,'mini_programs_id' => $mini_program]);
        $query = (new \yii\db\Query())
            ->select(['status','count(status) as count'])
            ->from(['t_order'])
            ->where(['mini_program'=>$mini_program,'user_id'=>$user_id])
            ->andWhere(['and','!isnull(status)'])
            ->groupBy('status')
            ->all();


//        $command = $query->createCommand();
//
//        $rows = $command->queryAll();
        return $this->renderJson($query, 0, 'sussess!');

    }

    /**
     * 获取订单
     * @return string
     */
    public function actionGetOrdersDetailByStatus()
    {
        $mini_program = $this->current_mini_program['id'];
        $user_id = $this->current_user['id'];
        $status = $this->_getRequestValue('status','');
        $query = (new Query())
            ->select('*')
            ->from('t_order as t1')
            ->where(['t1.user_id'=>$user_id,'t1.mini_program'=>$mini_program,'t1.is_deleted'=>0])
            ->andFilterWhere(['status'=>$status])
            ->orderBy('t1.create_datetime desc')
            ->all();

        if(empty($query))
            return $this->renderJson(null, ApiResponseCode::OtherErrorCode, '没有订单哟!');


        foreach ($query as &$order){
            $goods_count = 0;
            $query1 = (new Query())
                ->select(['t1.id','t2.name','t4.url','t2.selling_price','t1.quantity'])
                ->from('t_order_goods as t1')
                ->leftJoin('t_goods as t2','t2.id=t1.goods_id')
                ->leftJoin('t_goods_image as t3','t3.goods_id = t2.id')
                ->leftJoin('t_file as t4','t3.file_id=t4.id')
                ->where(['t1.order_id'=>$order['id'],'t3.type'=>1])
                ->all();
            if(!empty($query1)) {
//                $goods_count = $goods_count + $query1['quantity'];
                foreach ($query1 as $goods){
                    $goods_count = $goods_count + $goods['quantity'];
                }
                $order['goods_count']=$goods_count;
                $order['goods'] = $query1;
            }
        }
        return $this->renderJson($query, 0, 'success!');
    }

    /**
     * 获取订单商品详情
     */
    public function actionGetOrderGoods(){
        $order_id = $this->_getRequestValue('order_id');
//        $order_goods_list = OrderGoods::findAll(['order_id'=>$order_id]);

        $order_goods_list = (new Query())
            ->select(['t1.*','t3.url','t4.total_selling_price','t4.receiver_name','receiver_phone','CONCAT(t4.receiver_province,t4.receiver_city,t4.receiver_region,t4.receiver_address) as address'])
            ->from('t_order_goods as t1')
            ->leftJoin('t_goods_image as t2','t1.goods_id = t2.goods_id')
            ->leftJoin('t_file as t3','t3.id = t2.file_id')
            ->leftJoin('t_order as t4','t4.id = t1.order_id')
            ->where(['order_id'=>$order_id])
            ->andWhere(['or','t2.`type`=1',['or','isnull(t2.`type`)']])
            ->all();

        return $this->renderJson($order_goods_list,empty($order_goods_list) ? 100 : 0,empty($order_goods_list) ? 'fail':'success');
    }

    /**
     * 付款
     * @return string
     */
    public function actionPay(){
        $order_id = $this->_getRequestValue('order_id');

//        $total_pay = $this->_getRequestValue('total_pay');

        $order = Order::findOne($order_id);
        //产品名称
        $body = '';
        $orderGoods = OrderGoods::find()
            ->where(['order_id'=>$order->id])
            ->all();

        foreach ($orderGoods as $goods){
//            var_dump($goods);

            if(!empty($goods) && !empty($goods->goods_name))
            $body = $body . $goods->goods_name;
        }


//        $bizcontent = "{\"body\":\"我是测试数据\","
//            . "\"subject\": \"App支付测试\","
//            . "\"out_trade_no\": \"09090990\","
//            . "\"timeout_express\": \"30m\","
//            . "\"total_amount\": \"0.01\","
//            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
//            . "}";
//        echo $bizcontent;

//        echo '------';

        $bizcontent = "{\"body\":\"$body\","
            . "\"subject\": \"商品订单\","
            . "\"out_trade_no\": \"$order->id\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"$order->total_selling_price\","
            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
            . "}";
//        echo $bizcontent;

        $data = ZfbService::getPayOrderStr($bizcontent);

        return $this->renderJson($data, 0, 'success!');
    }

    /**
     * 获取店铺街列表
     * @return [type] [description]
     * @author milloc
     * @date   2018-04-16
     */
    public function actionGetStoresList()
    {
        $page = $this->_getRequestValue('page', 0);
        $page_size = $this->_getRequestValue('pageSize', 20);

        $stores = (new EShopExt)->getSubEshopList($this->current_mini_program['id'], $page, $page_size);
        return $this->renderJson($stores);
    }

    /**
     * 获取商店的主页
     * 包括商店信息 总商品数量 推荐商品数量 最新商品数量
     * @return [type] [description]
     * @author milloc
     * @date   2018-04-16
     */
    public function actionGetStoreIndex()
    {
        $store_id = $this->_getRequestValue('store_id');
        // 获取商店信息
        $store = EShopExt::find()->select(['id', 'name', 'logo_url', 'sales_volume', 'favorite', 'publicity_url'])->where(['id' => $store_id, 'is_on' => 1])->asArray()->one();
        // 获取商品的数量
        $items_total_count = $store ? GoodsExt::getGoodsCount('', $this->current_mini_program['id'], $store_id) : 0;
        $items_recommend_count = $store ? GoodsExt::getRecommendGoodsCount($this->current_mini_program['id'], $store_id) : 0;
        $items_newest_count = $store ? GoodsExt::getNewestGoodsCount($this->current_mini_program['id'], $store_id) : 0;

        $data = ['store' => $store, 'items' => ['total_count' => $items_total_count, 'recommend_count' => $items_recommend_count, 'newest_count' => $items_newest_count]];
        return $this->renderJson($data);
    }

    /**
     * 获取商店的货物
     * @return [type] [description]
     * @author milloc
     * @date   2018-04-17
     */
    public function actionGetStoreGoodsList()
    {
        $store_id = $this->_getRequestValue('store_id');
        $page = $this->_getRequestValue('page', 0);
        $page_size = $this->_getRequestValue('page_size', 20);

        $data = GoodsExt::getGoodsListByShop($store_id, $page, $page_size);
        return $this->renderJson($data);
    }

    /**
     * 获取商店的介绍信息
     * 简明介绍 位置
     * @return [type] [description]
     * @author milloc
     * @date   2018-04-16
     */
    public function actionGetStoreDetail()
    {
        $store_id = $this->_getRequestValue('store_id');

        $store = EShopExt::find()->select(['name', 'logo_url', 'publicity_url', 'brief_introduction', 'lan', 'lat'])->where(['mini_programs_id' => $this->current_mini_program['id'], 'id' => $store_id])->asArray()->one();
        return $this->renderJson($store);
    }
}